'''
    Ice Channel
    WDMA
    By SJoneZ
'''

from entertainment.plugnplay.interfaces import MovieSource
from entertainment.plugnplay.interfaces import TVShowSource
from entertainment.plugnplay.interfaces import CustomSettings
from entertainment.plugnplay import Plugin
from entertainment import common
from entertainment.net import Net
import xbmc, re, os

class SJWDMA(MovieSource, TVShowSource, CustomSettings):
    implements = [MovieSource, TVShowSource, CustomSettings]

    import xbmcaddon

    addon_id = 'script.icechannel.extn.sjwdma'
    addon = xbmcaddon.Addon(addon_id)
    
    name = "SJ-WDMA"
    display_name = "WDMA"
    useragent = 'android-async-http/1.4.1 (http://loopj.com/android-async-http)'
    datapath = xbmc.translatePath(addon.getAddonInfo('profile'))
    torrent_path = os.path.join(datapath, 'torrents')
    cookie_path = os.path.join(datapath, 'cookies')
    profile = os.path.join(datapath,'WDMA')
    
    source_enabled_by_default = 'false'

    if not os.path.exists(datapath):
        os.makedirs(datapath)
    
    def __init__(self):
        xml = '<settings>\n'
        xml += '<category label="General">\n'
        xml += '<setting id="custom_urls" type="labelenum" label="URL" default="http://wdma/" values="Custom|http://wdma/" />\n'
        xml += '<setting id="custom_text_url" type="text" label="     Custom" default="" enable="eq(-1,0)" />\n'
        xml += '<setting id="torrent_folder" type="folder" label="Torrent Download Path" default="' + self.torrent_path + '" />\n'
	xml += '<setting id="torrent_replace" type="text" label="Replace Torrent Path on Play" default="" />\n'
	xml += '<setting id="player_win" type="bool" label="Player is Windows" default="false"/>'
	xml += '</category>\n'
        xml += '<category label="Account">\n'
        xml += '<setting id="wdma_user" type="text" label="Username" default="" />\n'
        xml += '<setting id="wdma_pwd" type="text" option="hidden" label="Password" default="" />'
        xml += '</category>\n' 
        xml += '</settings>\n'
        
        self.CreateSettings(self.name, self.display_name, xml)

    def get_torrent_path(self):
        tpath = self.Settings().get_setting('torrent_folder')
        if tpath == '':
            tpath = self.torrent_path
        if os.path.exists(tpath) == False:
            os.makedirs(tpath)
        return tpath

    def get_torrent_play_path(self, local_path, url):
        play_path = local_path
        replace_path = self.Settings().get_setting('torrent_replace')
        if replace_path != '':
            play_path = replace_path + url + '.torrent'
        #xbmc.getCondVisibility('system.platform.windows'):
        if self.Settings().get_setting('player_win'):
            return 'plugin://plugin.video.p2p-streams/?url=file:/' + play_path + '&mode=1&name=' + url
        else:
            return 'plugin://plugin.video.p2p-streams/?url=file:///' + play_path + '&mode=1&name=' + url

    def get_url(self):
        custom_url = self.Settings().get_setting('custom_urls')
        if custom_url == 'Custom':
            custom_url = self.Settings().get_setting('custom_text_url')
        if not custom_url.startswith('http'):
            custom_url = ('http://' + custom_url)
        if not custom_url.endswith('/'):
            custom_url += '/'
        return custom_url

    def get_cookie_jar(self):
        cookie_jar = os.path.join(self.cookie_path, "wdma.lwp")
        if os.path.exists(self.cookie_path) == False:
                os.makedirs(self.cookie_path)
        return cookie_jar
        
    def downloadFile(self,url,dest,silent = False,cookie = None):
        try:
            import urllib2
            file_name = url.split('/')[-1]
            print "Downloading: %s" % (file_name)
            if cookie:
                import cookielib
                cookie_file = os.path.join(self.cookie_path, cookie)
                cj = cookielib.LWPCookieJar()
                if os.path.exists(cookie_file):
                    try: cj.load(cookie_file,True)
                    except: cj.save(cookie_file,True)
                else: cj.save(cookie_file,True)
                opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
            else:
                opener = urllib2.build_opener()
            opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')]
            u = opener.open(url)
            f = open(dest, 'wb')
            meta = u.info()
            if meta.getheaders("Content-Length"):
                file_size = int(meta.getheaders("Content-Length")[0])
            else: file_size = 'Unknown'
            file_size_dl = 0
            block_sz = 8192
            while True:
                buffer = u.read(block_sz)
                if not buffer: break
                file_size_dl += len(buffer)
                f.write(buffer)
                #status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
                #status = status + chr(8)*(len(status)+1)
                #print status,
            print "Downloaded: %s %s Bytes" % (file_name, file_size)
            f.close()
            return True
        except Exception, e:
            print 'Error downloading file ' + url.split('/')[-1]
            self.ErrorReport(e, 'Source website is down')
            return False

    def GetFileHostsForContent(self, title, name, year, season, episode, type, list, lock, message_queue):                 
        
        name = self.CleanTextForSearch(name)
       
        search_term = name
        mbox_url = ''
        vid_url = ''
        quality_dict = {'1080p':'1080P', '720p':'720P', '540p':'SD', '480p':'SD', '360p':'LOW', '240p':'LOW'}
        
        print 'looking for WDMA ' + type + ' Content: ' + search_term + ' (' + year + ')'

        self.Login(self.get_url())
        tmp = self.getContentByType(search_term, season, episode, year, type)
        
        if len(tmp) > 0:
            for torrent in tmp:
                try:
                    print 'found torrent [' + torrent[0] + ']: ' + torrent[1]
                    if self.IsValidVideo(torrent[1]):
                        print 'torrent is a video file'
                        quality = self.GetTorrentQuality(torrent[1])
                        print 'torrent quality is ' + quality
                        self.AddFileHost(list, quality_dict.get(quality, 'NA'), torrent[0], host='WDMA')
                    else:
                        print 'torrent is not a video file'
                        
                except Exception, e:
                    print 'Error parsing torrent information for torrent ' + torrent[0]
                    self.ErrorReport(e, 'Source website is down')
        else:
            print 'No WDMA links found'

    def GetTorrentQuality(self, name):
        quality_types = ['720p','1080p']
        
        for quality in quality_types:
            if quality in name.lower():
                return quality       
        return '540p'

    def IsValidVideo(self, name):
        video_types = ['avi', 'mp4', 'mkv', 'mpg', 'divx', 'wmv']

        if any('.' + ext.lower() in name.lower()[-5:] for ext in video_types):
            return True
        else:
            return False

    def Resolve(self, url):
        torrent_url = self.get_url() + 'd.php?r=' + url
        torrent_file = os.path.join(self.get_torrent_path(), url + '.torrent')
        if os.path.exists(torrent_file) == True:
            os.remove(torrent_file)
        self.downloadFile(torrent_url, torrent_file, False, 'wdma.lwp')
        return self.get_torrent_play_path(torrent_file, url)

    def Login(self, url):
        import re        
        from entertainment.net import Net
        net = Net(cached=False,user_agent=self.useragent)
        wdma_user = self.Settings().get_setting('wdma_user')
        wdma_pwd = self.Settings().get_setting('wdma_pwd')
        loginurl = url + '/blog/wp-login.php'
        data     = {'_method':'POST','pwd': wdma_pwd,
                                            'log': wdma_user}
        headers  = {'Origin':url,
                                            'Referer':loginurl,
                                                    'X-Requested-With':'XMLHttpRequest'}
        html = net.http_POST(loginurl, data, headers)
        net.save_cookies(self.get_cookie_jar())

    def getContentByType(self, encode, season, episode, year, type):
        import re        
        from entertainment.net import Net
        try:
            returnList=[]
            custom_url = self.get_url()
            encode = encode.replace('%20',' ')

            # Build the search string
            if type == 'movies':
                # E.g. Guardians?Of?The?Galaxy*2014
                encode = encode.replace('.','*')
                encode = encode.replace(':','*')
                encode = encode.replace('-','*')
                encode = encode.replace(' ','?')
                encode = encode.replace('\'s','*s')
                encode = encode + '*' + year
            else:
                # E.g. The?Big?Bang?Theory*s07e01
                encode = encode.replace('.','*')
                encode = encode.replace(':','*')
                encode = encode.replace('-','*')
                encode = encode.replace(' ','?')
                encode = encode.replace('\'s','*s')
                encode = encode + '*s' + str(season).zfill(2) + 'e' + str(episode).zfill(2)

            print 'WDMA Search String is: ' + encode
            search_url = custom_url + 't.php?search='
            data     = {'_method':'POST','search': encode}
            headers  = {'Origin':custom_url,'Referer':search_url,'X-Requested-With':'XMLHttpRequest'}
            net = Net(cached=False,user_agent=self.useragent)
            net.set_cookies(self.get_cookie_jar())
            html = net.http_GET(search_url + encode, headers).content
            #print html

            returnList=re.compile('<a href="s\.php\?r=(.+?)">(.+?)</a>').findall(html)

            return returnList
        
        except Exception, e:
            self.ErrorReport(e, 'Source website is down')
            return []
            
    def ErrorReport(self, e, msg):
        print str(e)
        elogo = xbmc.translatePath('special://home/addons/script.icechannel.extn.sjwdma/resources/redx.png')
        xbmc.executebuiltin("XBMC.Notification([COLOR=FFFF0000]WDMA Error[/COLOR],"+msg+",10000,"+elogo+")")
        xbmc.log('***********WDMA Error: '+str(e)+'**************', xbmc.LOGERROR)
